package dbTools.tableInfo.field.fieldInfo.resolve.resolvers;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import dbTools.tableInfo.field.fieldInfo.resolve.IResolver;
import dbTools.tableInfo.field.fieldInfo.type.Type;
import dbTools.tableInfo.field.fieldInfo.type.types.TypeReference;

public class RefReslover implements IResolver {

	private final String KEY="参照：";
	
	@Override
	public void resolveContent(List<Type> typeList,String content) {

		String[] conts=content.split("\n");
		
		for(String cont: conts)
		{
			if(cont.contains(KEY)==false){
				continue;
			}
			
			//match [***].[***]
			String pstr="\\[(.*?)\\].\\[(.*?)\\]";	
			//match [***]
			String pstr2="\\[(.*?)\\]";	
			
			Pattern pattern = Pattern.compile(KEY+pstr);  
			Matcher m = pattern.matcher(cont);
			
			boolean result = m.find();
			if(!result)
			{
				continue;
			}
			
			String mainCont=m.group();
			
			TypeReference type=new TypeReference();
			
			//main
			pattern = Pattern.compile(pstr2); 
			m = pattern.matcher(mainCont);
			result = m.find();
			if(result)
			{
				type.setReferenceId(m.group().substring(1, m.group().length()-1));
				type.setReferenceId(type.getReferenceId().substring(0,1).toUpperCase()+ type.getReferenceId().substring(1));
				result = m.find();
				
				if(result)
				{
					type.setReferenceField(m.group().substring(1, m.group().length()-1));
					if(type.getReferenceField() !=null
						&& type.getReferenceField().length()==type.getReferenceField().getBytes().length
						&& Pattern.matches("[a-z]", type.getReferenceField().substring(1,2)))
					{
						type.setReferenceField(type.getReferenceField().substring(0,1).toLowerCase()+ type.getReferenceField().substring(1));
							
					}
				}
			}
			
			//種別
			pattern = Pattern.compile("種別="+pstr2); 
			m = pattern.matcher(cont);
			result = m.find();
			if(result)
			{
				type.setRefrenceType(m.group().substring(4, m.group().length()-1));
			}
			
			//フィルタ=
			pattern = Pattern.compile("フィルタ="+pstr2); 
			m = pattern.matcher(cont);
			result = m.find();
			if(result)
			{
				type.setFilter(m.group().substring(6, m.group().length()-1));
			}
			
			typeList.add(type);
		}
	}

}
